package org.ghost.springboot2.demo.config;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
@EnableAsync
public class TaskExecutorConfig implements AsyncConfigurer {
    public AsyncTaskExecutor getAsyncTaskExecutor() {
        return Singleton.INSTANCE.getInstance();
    }

    @Override
    public Executor getAsyncExecutor() {
        return Singleton.INSTANCE.getInstance();
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }

    private enum Singleton {
        /**
         * 实例
         */
        INSTANCE;

        private ThreadPoolTaskExecutor taskExecutor = null;

        Singleton() {
            taskExecutor = new ThreadPoolTaskExecutor();
            taskExecutor.setCorePoolSize(2);
            taskExecutor.setMaxPoolSize(Runtime.getRuntime().availableProcessors());
            taskExecutor.setQueueCapacity(500);
            taskExecutor.initialize();
        }

        public ThreadPoolTaskExecutor getInstance() {
            return taskExecutor;
        }
    }
}
